package com.pinion.controller.business;

import com.base.config.Constant;
import com.jfinal.kit.PathKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.render.JsonRender;
import com.jfinal.upload.UploadFile;
import com.pinion.model.T_Goods;
import com.pinion.model.T_Goods_Type;
import com.pinion.model.T_Goods_Type_Picture;
import com.zh_new.annotation.RouteBind;
import com.zh_new.controller.BaseController;

import java.io.File;
import java.sql.SQLException;
import java.util.List;

@RouteBind(path = "/Main/GoodsType", viewPath = "/Business/GoodsType")
public class GoodsTypeController extends BaseController {

    private static final Logger log = Logger.getLogger(GoodsTypeController.class);

    private String navTabId = "GoodsType";
    private String goodsTypePictureViewNavTabId = "GoodsTypePictureView";

    String webRoot = PathKit.getWebRootPath().replace(File.separator, "/");
    private int maxPostSize = Constant.MAX_POST_SIZE;

    /**
     * 商品类型主页
     */
    public void main() {
        String select = "SELECT *";
        int pageSize = Constant.PAGE_SIZE;
        int pageNumber = 1;
        try {
            if (null != getPara("numPerPage") && !"".equals(getPara("numPerPage").trim())) {
                pageSize = getParaToInt("numPerPage");
            }
            if (pageSize <= 0) {
                throw new Exception();
            }
            if (null != getPara("pageNum") && !"".equals(getPara("pageNum").trim())) {
                pageNumber = getParaToInt("pageNum");
            }
            if (pageNumber <= 0) {
                throw new Exception();
            }
        } catch (Exception e) {
            log.error("您提交的查询参数有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的查询参数有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        String sqlExceptSelect = "FROM t_goods_type";
        try {
            Page<T_Goods_Type> page = T_Goods_Type.dao.paginate(pageNumber, pageSize, select, sqlExceptSelect);
            setAttr("page", page);
            render("main.jsp");
        } catch (Exception e) {
            log.error("服务器存在错误，数据读取失败！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "服务器存在错误，数据读取失败！", "", "", "", "");
        }
    }

    /**
     * 商品类型添加页面
     */
    public void addip() {
        render("add.jsp");
    }

    /**
     * 商品类型添加处理
     */
    public void add() {
        if (null == getPara("t_Goods_Type.number") || 0 == getPara("t_Goods_Type.number").trim().length()) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        List<T_Goods_Type> list = T_Goods_Type.dao.list(getPara("t_Goods_Type.number"));
        if (null != list && 0 < list.size()) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，类型编号已经存在，不能重复！", "", "", "", "");
            return;
        }
        try {
            if (getModel(T_Goods_Type.class).save()) {
                toDwzJson(Constant.STATUS_CODE_OK, "商品类型添加完成！", navTabId, "", "closeCurrent", "");
            } else {
                toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
            }
        } catch (Exception e) {
            log.error("数据处理存在错误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
        }
    }


    /**
     * 商品类型修改页面
     */
    public void updateip() {
        Integer id;
        try {
            id = getParaToInt();
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        T_Goods_Type model = T_Goods_Type.dao.findById(id);
        if (null == model) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，商品类型不存在！", "", "", "", "");
            return;
        }
        setAttr("t_Goods_Type", model);
        render("update.jsp");
    }

    /**
     * 商品类型修改处理
     */
    public void update() {
        Integer id;
        try {
            id = getParaToInt("t_Goods_Type.id");
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        T_Goods_Type model = T_Goods_Type.dao.findById(id);
        if (null == model) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，商品类型不存在！", "", "", "", "");
            return;
        }
        if (!model.getStr("number").equals(getPara("t_Goods_Type.number"))) {
            List<T_Goods_Type> list = T_Goods_Type.dao.list(id, getPara("t_Goods_Type.number"));
            if (null != list && 0 < list.size()) {
                toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，商品类型编号已经存在，不能重复！", "", "", "", "");
                return;
            }
        }
        try {
            final T_Goods_Type goodsType = getModel(T_Goods_Type.class);
            Boolean succeed = Db.tx(new IAtom() {
                public boolean run() throws SQLException {
                    boolean value1;
                    boolean value2 = true;
                    if (value1 = goodsType.update()) {
                        value2 = T_Goods.dao.updateTypeInfo(goodsType.getInt("id"), goodsType.getStr("name"), goodsType.getStr("number"));
                    }
                    return value1 && value2;
                }
            });
            if (succeed) {
                toDwzJson(Constant.STATUS_CODE_OK, "商品类型修改完成！", navTabId, "", "closeCurrent", "");
            } else {
                toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
            }
        } catch (Exception e) {
            log.error("数据处理存在错误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
        }
    }

    /**
     * 商品类型删除处理
     */
    public void delete() {
        Integer id;
        try {
            id = getParaToInt();
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        T_Goods_Type model = T_Goods_Type.dao.findById(id);
        if (null == model) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，商品类型不存在！", "", "", "", "");
            return;
        }

        Long count = T_Goods.dao.countByType(id);
        if (count > 0) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "商品类型已经被引用，不能删除！", "", "", "", "");
            return;
        }
        try {
            if (model.delete()) {
                toDwzJson(Constant.STATUS_CODE_OK, "商品类型删除完成！", navTabId, "", "", "");
            } else {
                toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
            }
        } catch (Exception e) {
            log.error("数据处理存在错误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
        }
    }


    /**
     * 进入商品图片浏览页面
     */
    public void goodsTypePictureViewip() {
        String goods_type_number;
        try {
            goods_type_number = getPara("goods_type_number");
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        List<T_Goods_Type_Picture> pictureList = T_Goods_Type_Picture.dao.getByGoodsTypeNumber(goods_type_number);

        setAttr("goods_type_number", goods_type_number);
        setAttr("pictureList", pictureList);
        render("goodsTypePictureView.jsp");
    }

    /**
     * 进入上传商品类型图片页面
     */
    public void goodsTypePictureUploadip() {
        String goods_type_number;
        try {
            goods_type_number = getPara("goods_type_number");
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }

        setAttr("goods_type_number", goods_type_number);
        render("goodsTypePictureUpload.jsp");
    }

    /**
     * 上传商品类型图片处理
     */
    public void goodsTypePictureUpload() {
        try {
            UploadFile file = getFile("goods_type_picture", "images/goodstype", maxPostSize);
            String suffix = file.getFileName().substring(file.getFileName().lastIndexOf(".")+1, file.getFileName().length()).toLowerCase();
            if(!suffix.equals("jpg") && !suffix.equals("png") && !suffix.equals("bmp")) {
                toDwzJson(Constant.STATUS_CODE_ERROR, "只支持以jpg,png,bmp为后缀的图片文件！", "", "", "", "");
            }

            String goods_type_number = getPara("goods_type_number");
//            String picture_type = getPara("picture_type");
            String picture_type = "gt";

            if (null == goods_type_number || 0 == goods_type_number.trim().length()) {
                toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
                return;
            }
//            if (null == picture_type || 0 == picture_type.trim().length()) {
//                toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
//                return;
//            }

            int newIndex = T_Goods_Type_Picture.dao.getPicNewIndexByPicType(picture_type);
            String fileName = goods_type_number + "_" + picture_type + "_" + newIndex + "." + suffix;
            file.getFile().renameTo(new File(webRoot + "/" + "File/images/goodstype" + "/" + fileName));

            boolean result = new T_Goods_Type_Picture().set("goods_type_number", goods_type_number).set("url", "File/images/goodstype" + "/" + fileName).set("pic_name", fileName)
                    .set("pic_type", picture_type).set("pic_index", newIndex).save();

            if(result) {
                toDwzJson(Constant.STATUS_CODE_OK, "商品类型图片上传完成！", goodsTypePictureViewNavTabId, "", "closeCurrent", "");
            }

        } catch (Exception e) {
            log.error("上传图片出错，请检查后再提交！", e);
            render(new JsonRender("{\"err\":\"上传图片出错，请检查后再提交！\",\"msg\":\"\"}").forIE());
        }
    }

    /**
     * 商品图片类型删除处理
     */
    public void goodsTypePictureDelete() {
        Integer id;
        try {
            id = getParaToInt("id");
        } catch (Exception e) {
            log.error("您提交的数据有误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，请检查后重新提交！", "", "", "", "");
            return;
        }
        T_Goods_Type_Picture model = T_Goods_Type_Picture.dao.findById(id);
        if (null == model) {
            toDwzJson(Constant.STATUS_CODE_ERROR, "您提交的数据有误，商品类型图片不存在！", "", "", "", "");
            return;
        }
        model.set("is_delete", "1");
        try {
            if (model.update()) {
                toDwzJson(Constant.STATUS_CODE_OK, "商品类型图片删除完成！", goodsTypePictureViewNavTabId, "", "", "");
            } else {
                toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
            }
        } catch (Exception e) {
            log.error("数据处理存在错误，请检查后重新提交！", e);
            toDwzJson(Constant.STATUS_CODE_ERROR, "数据处理存在错误，请检查后重新提交！", "", "", "", "");
        }
    }

}
